package com.ssy.lingxi.platform.template.service.serviceimpl.web;

import cn.hutool.core.collection.CollectionUtil;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.member.MemberTypeEnum;
import com.ssy.lingxi.common.constant.member.RoleTypeEnum;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.api.feign.inner.MemberInnerControllerFeign;
import com.ssy.lingxi.member.merchant.api.feign.inner.MemberLevelRightCreditControllerFeign;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberFeignIdVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberFeignVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberFeignLrcVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberFeignRegisterQueryVO;
import com.ssy.lingxi.platform.manage.api.feign.inner.AreaControllerFeign;
import com.ssy.lingxi.platform.template.api.model.dto.inner.MemberPurchaseInnerDTO;
import com.ssy.lingxi.platform.template.service.constant.CommonBooleanEnum;
import com.ssy.lingxi.platform.template.service.constant.SeoDoorTypeEnum;
import com.ssy.lingxi.platform.template.service.constant.SeoTypeEnum;
import com.ssy.lingxi.platform.template.service.entity.collect.MemberPurchaseCollect;
import com.ssy.lingxi.platform.template.service.entity.door.MemberPurchase;
import com.ssy.lingxi.platform.template.service.entity.door.QMemberPurchase;
import com.ssy.lingxi.platform.template.service.entity.door.Seo;
import com.ssy.lingxi.platform.template.service.model.bo.AreaBO;
import com.ssy.lingxi.platform.template.service.model.dto.common.CollectDTO;
import com.ssy.lingxi.platform.template.service.model.dto.common.IdDTO;
import com.ssy.lingxi.platform.template.service.model.dto.common.MemberIdAndRoleIdDTO;
import com.ssy.lingxi.platform.template.service.model.dto.web.SavePurchaseDTO;
import com.ssy.lingxi.platform.template.service.model.qo.MemberPurchaseQO;
import com.ssy.lingxi.platform.template.service.model.vo.web.MemberPurchaseListVO;
import com.ssy.lingxi.platform.template.service.model.vo.web.MemberPurchaseMainVO;
import com.ssy.lingxi.platform.template.service.repository.MemberPurchaseCollectRepository;
import com.ssy.lingxi.platform.template.service.repository.MemberPurchaseRepository;
import com.ssy.lingxi.platform.template.service.repository.SeoRepository;
import com.ssy.lingxi.platform.template.service.service.web.MemberPurchaseWebService;
import com.ssy.lingxi.product.api.feign.ICommodityFeign;
import com.ssy.lingxi.product.api.model.request.MemberRequest;
import com.ssy.lingxi.product.api.model.response.store.StoreResponse;
import com.ssy.lingxi.report.api.feign.ReportControllerFeign;
import com.ssy.lingxi.report.api.vo.request.PurchasePortalRequest;
import com.ssy.lingxi.report.api.vo.response.ActiveMerchantVO;
import com.ssy.lingxi.report.api.vo.response.PurchasePortalStatisticsVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

/**
 * @author fhj
 * @version 2.0.0
 * @menu web - 会员采购门户 - 业务实现层
 * @date 2021/04/14
 */
@Slf4j
@Service
public class MemberPurchaseWebServiceImpl implements MemberPurchaseWebService {

    @Resource
    private JPAQueryFactory jpaQueryFactory;
    @Resource
    private MemberPurchaseRepository memberPurchaseRepository;
    @Resource
    private MemberLevelRightCreditControllerFeign memberLevelRightCreditControllerFeign;
    @Resource
    private MemberInnerControllerFeign memberInnerControllerFeign;
    @Resource
    private AreaControllerFeign areaControllerFeign;
    @Resource
    private ICommodityFeign commodityFeign;
    @Resource
    private MemberPurchaseCollectRepository memberPurchaseCollectRepository;
    @Resource
    private SeoRepository seoRepository;
    @Resource
    private ReportControllerFeign reportControllerFeign;

    @Override
    @Transactional
    @ApiOperation(value = "保存当前登录会员的采购门户")
    public Wrapper<Void> saveCurrMemberPurchase(SavePurchaseDTO dto, UserLoginCacheDTO user) {
        //校验（只有是服务消费者且企业类型是企业会员或个人会员才能创建采购门户）
        if (!user.getMemberRoleType().equals(RoleTypeEnum.SERVICE_CONSUMER.getCode())) {
            return Wrapper.fail("角色类型不是服务消费者, 不能创建采购门户");
        }
        if (!(user.getMemberType().equals(MemberTypeEnum.MERCHANT.getCode()) || user.getMemberType().equals(MemberTypeEnum.MERCHANT_PERSONAL.getCode()))) {
            return Wrapper.fail("会员类型不是企业会员或个人会员, 不能创建采购门户");
        }

        //默认省、市编码都为0（所有/所有）
        List<String> provinceCodes = Stream.of("0").collect(toList());
        List<String> cityCodes = Stream.of("0").collect(toList());
        if (dto.getAreaBOList().stream().noneMatch(a -> a.getProvinceCode().equals("0"))) {
            provinceCodes = dto.getAreaBOList().stream().map(AreaBO::getProvinceCode).collect(Collectors.toList());
            cityCodes = dto.getAreaBOList().stream().filter(a -> !a.getCityCode().equals("0")).map(AreaBO::getCityCode).collect(Collectors.toList());

            List<String> feignCodes = dto.getAreaBOList().stream().filter(a -> a.getCityCode().equals("0")).map(AreaBO::getProvinceCode).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(feignCodes)) {
                Wrapper<List<String>> cityCodesWrapper = areaControllerFeign.findCityCodeByProvinceCode(feignCodes);
                if (cityCodesWrapper.getCode() == ResponseCode.SUCCESS.getCode() && CollectionUtil.isNotEmpty(cityCodesWrapper.getData())) {
                    cityCodes.addAll(cityCodesWrapper.getData());
                }
            }
        }

        //调用会员服务 -> 根据会员ID和角色ID获取平台会员的等级、注册年数、信用积分
        MemberFeignVO memberFeignVO = new MemberFeignVO();
        memberFeignVO.setMemberId(user.getMemberId());
        memberFeignVO.setRoleId(user.getMemberRoleId());
        Wrapper<MemberFeignLrcVO> platformMemberLrcWrapper = memberLevelRightCreditControllerFeign.getPlatformMemberLrc(memberFeignVO);
        if (platformMemberLrcWrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.error("调用会员服务失败：{}", platformMemberLrcWrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_MERCHANT_MEMBER_ERROR);
        }
        //调用会员服务 -> 根据会员Id查询会员注册信息
        MemberFeignIdVO memberFeignIdVO = new MemberFeignIdVO();
        memberFeignIdVO.setMemberId(user.getMemberId());
        Wrapper<MemberFeignRegisterQueryVO> memberRegisterInfoWrapper = memberInnerControllerFeign.getMemberRegisterInfo(memberFeignIdVO);
        if (memberRegisterInfoWrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.error("调用会员服务失败：{}", memberRegisterInfoWrapper.getMessage());
        }

        //保存会员采购门户信息
        MemberPurchase memberPurchase = memberPurchaseRepository.findByMemberIdAndRoleId(user.getMemberId(), user.getMemberRoleId());
        memberPurchase = memberPurchase != null ? memberPurchase : new MemberPurchase();
        memberPurchase.setMemberId(user.getMemberId());
        memberPurchase.setRoleId(user.getMemberRoleId());
        memberPurchase.setAreaBOList(dto.getAreaBOList());
        memberPurchase.setLogo(dto.getLogo());
        memberPurchase.setDescribe(dto.getDescribe());
        memberPurchase.setSlideshowBOList(dto.getSlideshowBOList());
        memberPurchase.setCompanyPics(dto.getCompanyPics());
        memberPurchase.setHonorPics(dto.getHonorPics());
        memberPurchase.setAdvertPics(dto.getAdvertPics());
        memberPurchase.setAlbumName(dto.getAlbumName());
        memberPurchase.setAlbumUrl(dto.getAlbumUrl());
        memberPurchase.setAreas(dto.getAreaBOList().stream().map(a -> a.getProvince() + "/" + a.getCity()).collect(Collectors.joining("，")));
        memberPurchase.setProvincesCodeList(String.join("，", provinceCodes));
        memberPurchase.setCityCodeList(String.join("，", cityCodes));
        memberPurchase.setMemberName(user.getCompany());
        memberPurchase.setLevelTag(platformMemberLrcWrapper.getData().getLevelTag());
        memberPurchase.setRegisterYears(platformMemberLrcWrapper.getData().getRegisterYears());
        memberPurchase.setCreditPoint(platformMemberLrcWrapper.getData().getCreditPoint());
        memberPurchase.setRegisteredCapital(memberRegisterInfoWrapper.getData() != null ? memberRegisterInfoWrapper.getData().getRegisteredCapital() : null);
        memberPurchase.setEstablishmentDate(memberRegisterInfoWrapper.getData() != null ? memberRegisterInfoWrapper.getData().getEstablishmentDate() : null);
        memberPurchase.setBusinessLicence(memberRegisterInfoWrapper.getData() != null ? memberRegisterInfoWrapper.getData().getBusinessLicence() : null);
        memberPurchase.setRegisterArea(memberRegisterInfoWrapper.getData() != null ? memberRegisterInfoWrapper.getData().getRegisterArea() : null);
        memberPurchase.setRegisterAddress(memberRegisterInfoWrapper.getData() != null ? memberRegisterInfoWrapper.getData().getRegisterAddress() : null);
        memberPurchase.setProvinceName(memberRegisterInfoWrapper.getData() != null ? memberRegisterInfoWrapper.getData().getProvinceName() : null);
        memberPurchase.setCityName(memberRegisterInfoWrapper.getData() != null ? memberRegisterInfoWrapper.getData().getCityName() : null);
        memberPurchaseRepository.saveAndFlush(memberPurchase);

        return Wrapper.success();
    }

    @Override
    @ApiOperation(value = "获取当前登录会员的采购门户")
    public Wrapper<MemberPurchase> findCurrMemberPurchase(UserLoginCacheDTO user) {
        return Wrapper.success(memberPurchaseRepository.findByMemberIdAndRoleId(user.getMemberId(), user.getMemberRoleId()));
    }

    @Override
    @ApiOperation(value = "采购门户列表")
    public Wrapper<PageData<MemberPurchaseListVO>> memberPurchaseList(MemberPurchaseQO qo) {
        //查询表实体 - 采购门户
        QMemberPurchase memberPurchase = QMemberPurchase.memberPurchase;

        //查询条件构造 - 搜索条件
        BooleanBuilder predicates = new BooleanBuilder();

        //搜索条件 - 平台品类ID。调用商品服务 -> 通过平台品类id查询会员ID集合，根据会员ID过滤采购门户。
        if (qo.getCategoryId() != null) {
            Wrapper<List<Long>> getMemberIdListWrapper = commodityFeign.getMemberIdList(qo.getCategoryId());
            if (getMemberIdListWrapper.getCode() == ResponseCode.SUCCESS.getCode()) {
                if (CollectionUtil.isNotEmpty(getMemberIdListWrapper.getData())) {
                    predicates.and(memberPurchase.memberId.in(getMemberIdListWrapper.getData()));
                } else {
                    return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
                }
            } else {
                log.info("请求商品服务失败:{}", getMemberIdListWrapper.getMessage());
            }
        }
        //搜索条件 - 会员名称。
        if (StringUtils.isNotBlank(qo.getMemberName())) {
            predicates.and(memberPurchase.memberName.like("%" + qo.getMemberName() + "%"));
        }
        //搜索条件 - 省编码。
        if (StringUtils.isNotBlank(qo.getProvinceCode())) {
            predicates.and(
                    memberPurchase.provincesCodeList.like("%" + qo.getProvinceCode() + "%")
                            .or(memberPurchase.provincesCodeList.eq("0"))
            );
        }
        //搜索条件 - 市编码。
        if (StringUtils.isNotBlank(qo.getCityCode())) {
            predicates.and(
                    memberPurchase.cityCodeList.like("%" + qo.getCityCode() + "%")
                            .or(memberPurchase.cityCodeList.eq("0"))
            );
        }

        //查询
        JPAQuery<MemberPurchase> query = jpaQueryFactory.select(memberPurchase).from(memberPurchase).where(predicates);

        //总记录数
        long totalCount = query.fetchCount();

        //排序条件 - 信用积分
        if (qo.getSortCreditPoint() != null) {
            if (qo.getSortCreditPoint().equals("DESC")) {
                query.orderBy(memberPurchase.creditPoint.desc()).orderBy(memberPurchase.createTime.desc());
            }
            if (qo.getSortCreditPoint().equals("ASC")) {
                query.orderBy(memberPurchase.creditPoint.asc()).orderBy(memberPurchase.createTime.desc());
            }
        } else {
            query.orderBy(memberPurchase.createTime.desc());
        }

        //列表数据
        List<MemberPurchase> list = query.offset((long) (qo.getCurrent() - 1) * qo.getPageSize()).limit(qo.getPageSize()).fetch();
        if (CollectionUtil.isEmpty(list)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        //调用商品服务 -> 根据会员ID和角色ID集合获取采购门户的主营分类
        Map<String, StoreResponse> map = commodityFeign.getCommodityAndCategoryByMemberIdAndMemberRoleId(
                list.stream().map(a -> {
                    MemberRequest memberRequest = new MemberRequest();
                    memberRequest.setMemberId(a.getMemberId());
                    memberRequest.setMemberRoleId(a.getRoleId());
                    return memberRequest;
                }).collect(toList())
        );

        //调用报表服务 -> 获得采购门户-采购信息统计列表
        Wrapper<List<PurchasePortalStatisticsVO>> wrapper = reportControllerFeign.getPurchasePortalStatisticsInfoList(
                list.stream().map(a -> {
                    PurchasePortalRequest request = new PurchasePortalRequest();
                    request.setMemberId(a.getMemberId());
                    request.setRoleId(a.getRoleId());
                    return request;
                }).collect(toList())
        );
        if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求报表服务失败:{}", wrapper.getMessage());
        }

        //封装每个采购门户的主营分类和采购金额、采购数量、询价数量、招标数量、竞价数量
        List<MemberPurchaseListVO> memberPurchaseListVOList = list.stream().map(a -> {
            MemberPurchaseListVO vo = new MemberPurchaseListVO();
            BeanUtils.copyProperties(a, vo);

            if (CollectionUtil.isNotEmpty(map) && map.get(a.getMemberId() + "-" + a.getRoleId()) != null) {
                vo.setMainCategory(map.get(a.getMemberId() + "-" + a.getRoleId()).getCustomerCategoryName());
            }

            if (CollectionUtil.isNotEmpty(wrapper.getData())) {
                PurchasePortalStatisticsVO purchasePortalStatisticsVO = wrapper.getData().stream().filter(b ->
                        b.getMemberId().equals(a.getMemberId()) && b.getRoleId().equals(a.getRoleId())
                ).findFirst().orElse(null);
                if (purchasePortalStatisticsVO != null) {
                    vo.setPurchaseAmount(purchasePortalStatisticsVO.getAmount());
                    vo.setPurchaseNum(purchasePortalStatisticsVO.getNum());
                    vo.setInquiryNum(purchasePortalStatisticsVO.getInquiryNum());
                    vo.setInviteTenderNum(purchasePortalStatisticsVO.getInviteTenderNum());
                    vo.setBiddingNum(purchasePortalStatisticsVO.getBiddingNum());
                }
            }

            return vo;
        }).collect(toList());

        return Wrapper.success(new PageData<>(totalCount, memberPurchaseListVOList));
    }

    @Override
    @ApiOperation(value = "活跃采购商")
    public Wrapper<List<MemberPurchase>> activeMemberPurchase() {
        Wrapper<List<ActiveMerchantVO>> wrapper = reportControllerFeign.getActiveMerchantList();
        if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求报表服务失败:{}", wrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_REPORT_ERROR);
        }
        if (CollectionUtil.isEmpty(wrapper.getData())) {
            return Wrapper.success(new ArrayList<>());
        }
        List<String> idStr = wrapper.getData().stream().map(a -> a.getMemberId() + "-" + a.getRoleId()).collect(toList());

        List<MemberPurchase> memberPurchaseList = memberPurchaseRepository.findAll();
        if (CollectionUtil.isEmpty(memberPurchaseList)) {
            return Wrapper.success(new ArrayList<>());
        }

        return Wrapper.success(
                memberPurchaseList.stream().filter(a ->
                        idStr.contains((a.getMemberId() + "-" + a.getRoleId()))
                ).collect(toList())
        );
    }

    @Override
    @ApiOperation(value = "最新加入")
    public Wrapper<List<MemberPurchase>> newAddMemberPurchase() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 6);
        return Wrapper.success(memberPurchaseRepository.findNewAddMemberPurchase(calendar.getTimeInMillis()));
    }

    @Override
    @ApiOperation(value = "采购门户主页")
    public Wrapper<MemberPurchaseMainVO> memberPurchaseMain(IdDTO dto, Long memberId, Long roleId, UserLoginCacheDTO user) {
        //获取采购门户
        MemberPurchase memberPurchase;
        if (dto.getId().equals(0L)) {
            if (memberId == null || roleId == null) {
                return Wrapper.fail("会员ID或角色ID不能为空");
            }
            memberPurchase = memberPurchaseRepository.findByMemberIdAndRoleId(memberId, roleId);
        } else {
            memberPurchase = memberPurchaseRepository.findById(dto.getId()).orElse(null);
        }

        if (memberPurchase == null) {
            return Wrapper.fail("该采购商还未创建采购门户");
        }

        //拷贝
        MemberPurchaseMainVO memberPurchaseMainVO = new MemberPurchaseMainVO();
        BeanUtils.copyProperties(memberPurchase, memberPurchaseMainVO);

        //收藏状态
        if (user != null) {
            memberPurchaseMainVO.setCollectStatus(memberPurchaseCollectRepository.existsByPurchaseIdAndMemberIdAndUserId(memberPurchase.getId(), user.getMemberId(), user.getUserId()));
        }

        //调用商品服务 -> 根据会员ID和角色ID集合获取店铺的主营分类
        MemberRequest memberRequest = new MemberRequest();
        memberRequest.setMemberId(memberPurchaseMainVO.getMemberId());
        memberRequest.setMemberRoleId(memberPurchaseMainVO.getRoleId());
        Map<String, StoreResponse> map = commodityFeign.getCommodityAndCategoryByMemberIdAndMemberRoleId(
                Stream.of(memberRequest).collect(toList())
        );
        if (CollectionUtil.isNotEmpty(map) && map.get(memberPurchaseMainVO.getMemberId() + "-" + memberPurchaseMainVO.getRoleId()) != null) {
            memberPurchaseMainVO.setMainCategory(map.get(memberPurchaseMainVO.getMemberId() + "-" + memberPurchaseMainVO.getRoleId()).getCustomerCategoryName());
        }

        //获取采购SEO
        List<Seo> seoList = seoRepository.findAllByDoorTypeAndDoorIdAndStatus(
                SeoDoorTypeEnum.PURCHASE.getCode(),
                memberPurchase.getId(),
                CommonBooleanEnum.YES.getCode()
        );
        //封装采购SEO(首页、关于我们)
        if (CollectionUtil.isNotEmpty(seoList)) {
            Seo homePage = seoList.stream().filter(a -> a.getType().equals(SeoTypeEnum.HOME_PAGE.getCode())).findFirst().orElse(null);
            Seo aboutUs = seoList.stream().filter(a -> a.getType().equals(SeoTypeEnum.ABOUT_US.getCode())).findFirst().orElse(null);
            memberPurchaseMainVO.setHomePage(homePage);
            memberPurchaseMainVO.setAboutUs(aboutUs);
        }

        //调用报表服务 -> 获得采购门户-采购信息统计
        PurchasePortalRequest request = new PurchasePortalRequest();
        request.setMemberId(memberPurchaseMainVO.getMemberId());
        request.setRoleId(memberPurchaseMainVO.getRoleId());
        Wrapper<PurchasePortalStatisticsVO> wrapper = reportControllerFeign.getPurchasePortalStatisticsInfo(request);
        if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求报表服务失败:{}", wrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_REPORT_ERROR);
        }
        if (wrapper.getData() != null) {
            memberPurchaseMainVO.setPurchaseAmount(wrapper.getData().getAmount());
            memberPurchaseMainVO.setPurchaseNum(wrapper.getData().getNum());
            memberPurchaseMainVO.setInquiryNum(wrapper.getData().getInquiryNum());
            memberPurchaseMainVO.setInviteTenderNum(wrapper.getData().getInviteTenderNum());
            memberPurchaseMainVO.setBiddingNum(wrapper.getData().getBiddingNum());
        }

        return Wrapper.success(memberPurchaseMainVO);
    }

    @Override
    @ApiOperation(value = "根据会员ID和角色ID获取采购门户")
    public Wrapper<MemberPurchaseMainVO> findByMemberIdAndRoleId(MemberIdAndRoleIdDTO dto) {
        //获取采购门户
        MemberPurchase memberPurchase = memberPurchaseRepository.findByMemberIdAndRoleId(dto.getMemberId(), dto.getRoleId());
        if (memberPurchase == null) {
            return Wrapper.fail("根据ID找不到采购门户");
        }

        //拷贝
        MemberPurchaseMainVO memberPurchaseMainVO = new MemberPurchaseMainVO();
        BeanUtils.copyProperties(memberPurchase, memberPurchaseMainVO);

        //调用报表服务 -> 获得采购门户-采购信息统计
        PurchasePortalRequest request = new PurchasePortalRequest();
        request.setMemberId(memberPurchaseMainVO.getMemberId());
        request.setRoleId(memberPurchaseMainVO.getRoleId());
        Wrapper<PurchasePortalStatisticsVO> wrapper = reportControllerFeign.getPurchasePortalStatisticsInfo(request);
        if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求报表服务失败:{}", wrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_REPORT_ERROR);
        }
        if (wrapper.getData() != null) {
            memberPurchaseMainVO.setPurchaseAmount(wrapper.getData().getAmount());
            memberPurchaseMainVO.setPurchaseNum(wrapper.getData().getNum());
            memberPurchaseMainVO.setInquiryNum(wrapper.getData().getInquiryNum());
            memberPurchaseMainVO.setInviteTenderNum(wrapper.getData().getInviteTenderNum());
            memberPurchaseMainVO.setBiddingNum(wrapper.getData().getBiddingNum());
        }

        return Wrapper.success(memberPurchaseMainVO);
    }

    @Override
    @Transactional
    @ApiOperation(value = "收藏/取消收藏")
    public Wrapper<Void> collect(CollectDTO dto, UserLoginCacheDTO user) {
        if (dto.getStatus()) {
            if (memberPurchaseCollectRepository.existsByPurchaseIdAndMemberIdAndUserId(dto.getId(), user.getMemberId(), user.getUserId())) {
                return Wrapper.fail("不能重复收藏，请刷新页面");
            }
            MemberPurchaseCollect collect = new MemberPurchaseCollect();
            collect.setPurchaseId(dto.getId());
            collect.setMemberId(user.getMemberId());
            collect.setUserId(user.getUserId());
            memberPurchaseCollectRepository.saveAndFlush(collect);
        } else {
            memberPurchaseCollectRepository.deleteByPurchaseIdAndMemberIdAndUserId(dto.getId(), user.getMemberId(), user.getUserId());
        }

        return Wrapper.success();
    }

    @Override
    @ApiOperation(value = "收藏列表")
    public Wrapper<PageData<MemberPurchase>> collectList(PageVO dto, UserLoginCacheDTO user) {
        //按收藏时间倒序获取当前用户收藏的采购门户ID
        Pageable pageable = PageRequest.of(dto.getCurrent() - 1, dto.getPageSize(), Sort.by("createTime").descending());
        Page<MemberPurchaseCollect> page = memberPurchaseCollectRepository.findAllByMemberIdAndUserId(user.getMemberId(), user.getUserId(), pageable);
        List<MemberPurchaseCollect> memberPurchaseCollectList = page.getContent();
        if (CollectionUtil.isEmpty(memberPurchaseCollectList)) {
            log.info("当前用户没有收藏的采购门户");
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }
        List<Long> memberPurchaseIdList = memberPurchaseCollectList.stream().map(MemberPurchaseCollect::getPurchaseId).collect(toList());

        //根据收藏的采购ID获取采购门户
        List<MemberPurchase> memberPurchaseList = memberPurchaseRepository.findAllById(memberPurchaseIdList);

        //组装收藏时间
        memberPurchaseList = memberPurchaseList.stream().peek(a -> a.setCreateTime(
                memberPurchaseCollectList.stream().filter(b ->
                        b.getPurchaseId().equals(a.getId())
                ).map(MemberPurchaseCollect::getCreateTime).findFirst().orElse(null)
        )).sorted(Comparator.comparingInt(a -> memberPurchaseIdList.indexOf(a.getId()))).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(page.getTotalElements(), memberPurchaseList));
    }

    @Override
    public Wrapper<Boolean> exitMemberPurchase(MemberPurchaseInnerDTO dto) {
        //判断是否存在采购门户
        return Wrapper.success(memberPurchaseRepository.existsByMemberIdAndRoleId(dto.getMemberId(), dto.getMemberRoleId()));
    }
}
